import { View, Text } from '@tarojs/components'
import Taro,{ useLoad,useDidShow } from '@tarojs/taro'
import './index.scss'
import { request } from "@/utils/request";
import { useState } from 'react';
import EmptyView from '@/components/EmptyView';
let jumpDetailTimeout = 500
let jumpDetailTimer = null as any
export default function PayOrderList () {
  // 获取缴费单列表
  const [orderList, setOrderList] = useState<any>([])
  const [loading,setLoading] = useState(true)
  // status状态列表
  function getStatusName(status){
    if(status == 0 ){
      return '未缴费'
    }else if(status == 1){
      return '已缴费'
    }else if(status == 2){
      return '已完成'
    }else {
      return '已取消'
    }
  }
  function getPayOrderList () {
    setLoading(true)
    request({
      url: '/api/payment/order/getPaymentOrders',
      method: 'POST',
      data: {},
      success: (data) => {
        // console.log(res)
        data.forEach(item=>{
          item.statusName = getStatusName(item.status)
        })
        setOrderList(data)
      },
      complete:()=>{
        setLoading(false)
      }
    })
  }
  // 立即缴费
  function payMoney(item){
    // console.log(item)
    clearTimeout(jumpDetailTimer)
    request({
      url:'/api/payment/order/payPaymentOrder/'+item.id,
      method: 'POST',
      data: {
        // 查询参数
        token: Taro.getStorageSync("token"),
        id: item.id
      },
      success: (data) => {
        console.log('payMoney data：',data)
        
        // console.log(res)
        let orderId = data.id
        const payInfo = data.paymentResponse
        if(payInfo){
          console.log('创建订单成功 payInfo:',payInfo)
          // 调微信支付
          let params = {
            appId: payInfo.appid,
            nonceStr: payInfo.nonceStr,
            package: 'prepay_id='+payInfo.prepayId, // 固定值，以微信支付文档为主
            timeStamp: payInfo.timestamp,
            paySign: payInfo.sign,
            signType: 'RSA' // 根据签名算法生成签名
          };
          // 调微信支付
          pay(params,orderId);
        }else{
          Taro.navigateTo({
            url: `/pages/paySuccess/index?orderId=${orderId}`,
          })
        }
        // getPayOrderList()
      },
      fail(code,message,data){
        Taro.showModal({
          title: '提示',
          content: message || '创建订单失败，请稍后重试',
          showCancel:false,
          confirmText:'确定'
        })
      },
    })
  }
  function pay(params,orderId) {
    Taro.requestPayment({
      ...params,
      success: (win) => {
        console.log('success win:',win)
        Taro.showLoading({
          title: '支付确认中',
          mask: true
        });
        setTimeout(async () => {
          // 支付成功后，跳转到支付成功结果页
          Taro.hideLoading();
          Taro.navigateTo({
            url: `/pages/paySuccess/index?orderId=${orderId}`,
          })
        }, 1500);
      },
      fail: (err) => {
        console.log('支付失败', err);
        Taro.showModal({
          title: '支付错误,请重试',
          showCancel: false,
          confirmText: '确定',
          success: (res) => {
            
          }
        });
      }
    });
  }
  function cancelOrder(item){
    clearTimeout(jumpDetailTimer)
    // 取消订单
    console.log('cancelOrder:',item)
    request({
      url: '/api/payment/order/cancelOrder/'+item.id,
      method: 'POST',
      data: {
        // 查询参数
        token: Taro.getStorageSync("token"),
        id: item.id
      },
      success: (data) => {
        console.log('取消成功')
        // console.log(res)
        getPayOrderList()
      }
    })
  }
  function jumpToDetail(item){
    clearTimeout(jumpDetailTimer)
    jumpDetailTimer = setTimeout(()=>{
      console.log('jumpToDetail item:',item)
      Taro.navigateTo({
        url: '/pages/payOrderDetail/index?id='+item.id
      })
    },jumpDetailTimeout)
    
    // console.log('jumpToDetail')
  }
  useLoad(() => {
    console.log('Page loaded.')
  })
  useDidShow(()=>{
    getPayOrderList()
  })

  return (
    <View className='payOrderList safe-bottom'>
      <View className='order-list' >
        {
          orderList.length > 0 && orderList.map(item => {
            return (
              <View className='order-item' onClick={()=>{ jumpToDetail(item)}}>
                <View className='order-item-header'>
                  <View className='title'>城乡居民医保代缴</View>
                  <View className='status'>{item.statusName}</View>
                </View>
                <View className='order-item-body'>
                  <View className='item'>参保人 {item.name}</View>
                  <View className='item'>参保地区 {item.provincesName} {item.cityName}</View>
                  <View className='item'>缴费年份 {item.year}年</View>
                </View>
                {
                  item.status == 0 && (
                    <View className='footer'>
                      <View className='btn' onClick={(event)=>{ event.stopPropagation();payMoney(item) }}>立即缴费</View>
                      <View className='btn' onClick={(event)=>{ event.stopPropagation();cancelOrder(item)}}>取消</View>
                    </View>
                  )
                }
              </View>
            )
          })
        }
        {
          !loading && orderList.length == 0 && <EmptyView emptyTxt='暂无缴费单' />
        }

      </View>
    </View>
  )
}
